package com._51doit.rpc

import java.util.UUID

import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._

/**
 * @create: 2021-10-08 19:28
 * @author: 珠穆朗玛峰顶峰的男人
 * @program: AKKaRpc
 **/
class Worker extends Actor {
  val workerId = UUID.randomUUID().toString

  //生命周期方法（按照一定顺序执行，并且必须执行）
  //在构造方法之后，receive方法之前，执行一次
  override def preStart(): Unit = {
    //先和Master建立连接
    val masterRef = context.actorSelection("akka.tcp://MasterActorSystem@127.0.0.1:8888/user/MasterActor")
    //向Master发送注册消息（workerId、内存、cpu核数）
    masterRef ! RegisterWorker(workerId, 10240, 16)

  }

  //接收消息的方法
  override def receive: Receive = {
    case RegisterWorker => {
      //启动一个定时器,定期向Master发送心跳
      import context.dispatcher
      context.system.scheduler.schedule(0 millisecond, 10000 millisecond, sender(), HeartBeat(workerId))
    }
  }
}

object Worker {

  def main(args: Array[String]): Unit = {

    val configStr =
      """
        |akka.actor.provider = "akka.remote.RemoteActorRefProvider"
        |akka.remote.netty.tcp.hostname = "127.0.0.1"
        |akka.remote.netty.tcp.port = 9999
        |""".stripMargin;

    val config = ConfigFactory.parseString(configStr)
    //创建 ActorSystem
    val workerActorSystem = ActorSystem("WorkerActorSystem", config)
    //创建Actor
    workerActorSystem.actorOf(Props[Worker], "WorkerActor")
  }

}
